import WxPay from "wechatpay-node-v3"; // "^2.2.0",
import fs from "fs";

// 直连商户 和服务商 都可用

const { WX_SP_MCHID, WX_SP_MP_ID, WX_SP_KEY_V3 } = process.env;
const rootDir = process.cwd() + "/pem/" + WX_SP_MCHID;

// const { MP_ID, WXPAY_MCHID, WXPAY_SERIAL, WXPAY_KEY_V3 } = process.env;
// openssl x509 -in apiclient_cert.pem -noout -serial

const wxpay = new WxPay({
  appid: WX_SP_MP_ID,
  mchid: WX_SP_MCHID, // 必须String类型
  publicKey: fs.readFileSync(rootDir + "/apiclient_cert.pem"), // 公钥
  privateKey: fs.readFileSync(rootDir + "/apiclient_key.pem"), // 秘钥
  userAgent: "Express-ice",
  // serial_no: "17318AB678D62CECEE51FD19EAD4DE4749E9807D",
  authType: "WECHATPAY2-SHA256-RSA2048",
  key: WX_SP_KEY_V3, // 退款用
});

function checkData(data) {
  if (data.error) throw JSON.parse(data.error);
  return data.data || data;
}

// https://github.com/klover2/wechatpay-node-v3-ts/blob/master/docs/transactions_jsapi.md
export async function getPrepay(params) {
  const data = await wxpay.transactions_jsapi(params);
  return checkData(data);
}

export function reSign(body) {
  const strToSign = [
    body.appId,
    body.timeStamp,
    body.nonceStr,
    body.package,
    "",
  ].join("\n");
  body.paySign = wxpay.sign(strToSign);
}

//https://github.com/klover2/wechatpay-node-v3-ts/blob/master/docs/query.md
export async function queryTrade(params) {
  const data = await wxpay.query(params); // { out_trade_no }
  return checkData(data);
}

// https://github.com/klover2/wechatpay-node-v3-ts/blob/master/docs/transactions_h5.md
export async function decipherGcm(params) {
  const { ciphertext, associated_data, nonce } = params;
  const data = await wxpay.decipher_gcm(
    ciphertext,
    associated_data,
    nonce
    // key
  );
  return checkData(data);
}

// https://pay.weixin.qq.com/docs/partner/apis/profit-sharing/receivers/add-receiver.html
export async function addProfitReceiver(params) {
  params.appid = WX_SP_MP_ID;
  if (params.name) {
    const cert = await getCert();
    params.name = wxpay.publicEncrypt(params.name, cert.publicKey);
    console.log(params);
  }
  const data = await wxpay.profitsharing_receivers_add(params);
  return checkData(data);
}

// https://github.com/klover2/wechatpay-node-v3-ts/blob/master/docs/profitsharing.md
// https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter8_1_8.shtml
export async function postProfitSharing(params) {
  const data = await wxpay.create_profitsharing_orders({
    unfreeze_unsplit: true,
    // wx_serial_no: WXPAY_SERIAL,
    ...params,
  });
  return checkData(data);
}

export async function getCert() {
  const list = await wxpay.get_certificates(WX_SP_KEY_V3);
  const certificate = list.pop();
  return certificate; // .serial_no;
}
